package com.hschinese.pronunciation.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ProgressBar;

/**
 * Created by wo on 2015/11/3.
 */
public class TextProgressBar extends ProgressBar {
    private String str;
    private Paint mPaint;

    public TextProgressBar(Context context){
        super(context);
        initText();
    }

    public TextProgressBar(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
        initText();
    }

    public TextProgressBar(Context context, AttributeSet attrs){
        super(context, attrs);
        initText();
    }

    @Override
    public void setProgressDrawable(Drawable d) {
        super.setProgressDrawable(d);
    }

    public void setProgress(int progress) {
       setText(progress);
        super.setProgress(progress);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Rect rect = new Rect();
        this.mPaint.getTextBounds(this.str, 0, this.str.length(), rect);
        int max = getMax();
        if (max == 0) max = 1;
        int x = (getWidth()/max) * getProgress() - (int)(rect.centerX()*2);
        int y = getHeight()/2 - rect.centerY();
//        Logger.e("xionghy --- width: " + x + "  -- height: " + y);
        canvas.drawText(this.str, x, y, this.mPaint);
    }

    private void initText(){
        this.mPaint = new Paint();
        this.mPaint.setTextSize(32);
        this.mPaint.setAntiAlias(true);
        this.mPaint.setColor(Color.WHITE);
    }

    // 设置文字内容
    private void setText(int progress){
        int i = (int) ((progress * 1.0f / this.getMax()) * 100);
        this.str = String.valueOf(i) + "%";
        str="";
    }
}
